//
//  SEGHTTPBusinessManager.m
//  SEGBasicBussiness
//
//  Created by 刘山 on 2018/3/14.
//  Copyright © 2018年 刘山. All rights reserved.
//

/*
 WKWebView 相关的资料
 https://www.cnblogs.com/NSong/p/6489802.html
 */

#import "SEGHTTPBusinessManager.h"
#import "SEGHTTPManager.h"

#if __has_include(<CommonMediator/SEGMediatorHeader.h>)
#import <CommonMediator/SEGMediatorHeader.h>
#else
#import "SEGMediatorHeader.h"
#endif

@implementation SEGHTTPBusinessManager
+(void)seg_uploadDatasWithURLString:(NSString*)URLString parameters:(id)parameters detailSources:(NSArray<SEGUploadFileModel*>*)detailSources progress:(void(^)(double progressValue))progress completed:(SEGReponseBlock)completed{
    URLString = [self seg_setRequestChangeUrl:URLString];
    [self seg_setRequestHeaderFieldWithUrlString:URLString];
    [self seg_setTimeoutIntervalWithUrlString:URLString];
    
    [[SEGHTTPManager sharedNetworkManager] uploadDatasWithURLString:URLString parameters:parameters sources:detailSources progress:progress completed:^(id result, NSError *error) {
        [self seg_responseLogicControlWithData:result error:error urlString:URLString completed:completed];
    }];
}

+(void)seg_uploadImageWithURLString:(NSString*)URLString parameters:(id)parameters source:(NSData*)source progress:(void(^)(double progressValue))progress completed:(SEGReponseBlock)completed{
    URLString = [self seg_setRequestChangeUrl:URLString];
    [self seg_setRequestHeaderFieldWithUrlString:URLString];
    [self seg_setTimeoutIntervalWithUrlString:URLString];
    [[SEGHTTPManager sharedNetworkManager] uploadImageWithURLString:URLString parameters:parameters source:source progress:progress completed:^(id result, NSError *error) {
        [self seg_responseLogicControlWithData:result error:error urlString:URLString completed:completed];
    }];
}

+(void)seg_uploadImageWithURLString:(NSString*)URLString parameters:(id)parameters source:(NSData*)source fileName:(NSString*)fileName progress:(void(^)(double progressValue))progress completed:(SEGReponseBlock)completed{
    URLString = [self seg_setRequestChangeUrl:URLString];
    [self seg_setRequestHeaderFieldWithUrlString:URLString];
    [self seg_setTimeoutIntervalWithUrlString:URLString];
    [[SEGHTTPManager sharedNetworkManager]uploadImageWithURLString:URLString parameters:parameters source:source fileName:fileName progress:progress completed:^(id result, NSError *error) {
        [self seg_responseLogicControlWithData:result error:error urlString:URLString completed:completed];
    }];
}

+(void)seg_uploadImagesWithURLString:(NSString*)URLString parameters:(id)parameters sources:(NSArray<NSData*>*)sources progress:(void(^)(double progressValue))progress completed:(SEGReponseBlock)completed{
    URLString = [self seg_setRequestChangeUrl:URLString];
    [self seg_setRequestHeaderFieldWithUrlString:URLString];
    [self seg_setTimeoutIntervalWithUrlString:URLString];
    [[SEGHTTPManager sharedNetworkManager]uploadImagesWithURLString:URLString parameters:parameters sources:sources progress:progress completed:^(id result, NSError *error) {
        [self seg_responseLogicControlWithData:result error:error urlString:URLString completed:completed];
    }];
}

/**
 上传多个mp3资源
 */
+(void)seg_uploadVoicesWithURLString:(NSString*)URLString parameters:(id)parameters sources:(NSArray<NSData*>*)sources progress:(void(^)(double progressValue))progress completed:(SEGReponseBlock)completed{
    URLString = [self seg_setRequestChangeUrl:URLString];
    [self seg_setRequestHeaderFieldWithUrlString:URLString];
    [self seg_setTimeoutIntervalWithUrlString:URLString];
    
    [[SEGHTTPManager sharedNetworkManager] uploadVoicesWithURLString:URLString parameters:parameters sources:sources progress:progress completed:^(id result, NSError *error) {
        [self seg_responseLogicControlWithData:result error:error urlString:URLString completed:completed];
    }];
}

/**
 上传单个mp3资源-默认文件名
 */
+(void)seg_uploadVoiceWithURLString:(NSString*)URLString parameters:(id)parameters source:(NSData*)source progress:(void(^)(double progressValue))progress completed:(SEGReponseBlock)completed{
    URLString = [self seg_setRequestChangeUrl:URLString];
    [self seg_setRequestHeaderFieldWithUrlString:URLString];
    [self seg_setTimeoutIntervalWithUrlString:URLString];
    
    [[SEGHTTPManager sharedNetworkManager] uploadVoiceWithURLString:URLString parameters:parameters source:source progress:progress completed:^(id result, NSError *error) {
        [self seg_responseLogicControlWithData:result error:error urlString:URLString completed:completed];
    }];
}

/**
 上传单个mp3资源-需要输入文件名
 */
+(void)seg_uploadVoiceWithURLString:(NSString*)URLString parameters:(id)parameters source:(NSData*)source fileName:(NSString*)fileName progress:(void(^)(double progressValue))progress completed:(SEGReponseBlock)completed{
    URLString = [self seg_setRequestChangeUrl:URLString];
    [self seg_setRequestHeaderFieldWithUrlString:URLString];
    [self seg_setTimeoutIntervalWithUrlString:URLString];
    
    [[SEGHTTPManager sharedNetworkManager] uploadVoiceWithURLString:URLString parameters:parameters source:source fileName:fileName progress:progress completed:^(id result, NSError *error) {
        [self seg_responseLogicControlWithData:result error:error urlString:URLString completed:completed];
    }];
}

+(void)seg_serRequestHeaderDictionary:(NSDictionary*)headers{
    if (!(headers && [headers isKindOfClass:[NSDictionary class]] && [headers allKeys].count > 0)) return;
    
    NSMutableDictionary *save = [NSMutableDictionary dictionary];
    NSArray *inputHeadArr = [headers allKeys];
    
    if ([inputHeadArr containsObject:@"platform"])  [save setValue:[headers valueForKey:@"platform"] forKey:@"platform"];
    if ([inputHeadArr containsObject:@"clientType"])  [save setValue:[headers valueForKey:@"clientType"] forKey:@"clientType"];
    if ([inputHeadArr containsObject:@"version"])  [save setValue:[headers valueForKey:@"version"] forKey:@"version"];
    if ([inputHeadArr containsObject:@"systemVersionCode"])  [save setValue:[headers valueForKey:@"systemVersionCode"] forKey:@"systemVersionCode"];
    if ([inputHeadArr containsObject:@"deviceId"])  [save setValue:[headers valueForKey:@"deviceId"] forKey:@"deviceId"];
    if ([inputHeadArr containsObject:@"SYSCODE"])  [save setValue:[headers valueForKey:@"SYSCODE"] forKey:@"SYSCODE"];
    if ([inputHeadArr containsObject:@"source"])  [save setValue:[headers valueForKey:@"source"] forKey:@"source"];
    if ([inputHeadArr containsObject:@"communityId"])  [save setValue:[headers valueForKey:@"communityId"] forKey:@"communityId"];
    if ([inputHeadArr containsObject:@"versionCode"])  [save setValue:[headers valueForKey:@"versionCode"] forKey:@"versionCode"];
    
    [[NSUserDefaults standardUserDefaults] setObject:headers forKey:@"NSUserDefaultRequestHeaderDictionary"];
}

/**
 * 浅层网络请求封装
 * 目的：网络请求可以集中处理，也可以解耦
 * 每个网络请求都附带一个模型文件承载服务器返回的数据
 * @author Sam
 */
+(void)seg_requestWithMethod:(SEGHTTPSessionManagerRequestMethod)method URLString:(NSString*)URLString parameters:(id)parameters completed:(SEGReponseBlock)completed{
    
    URLString = [self seg_setRequestChangeUrl:URLString];
    [self seg_setRequestHeaderFieldWithUrlString:URLString];
    [self seg_setTimeoutIntervalWithUrlString:URLString];
    
    [[SEGHTTPManager sharedNetworkManager] requestWithMethod:method URLString:URLString parameters:parameters finished:^(id result, NSError *error) {
        [self seg_responseLogicControlWithData:result error:error urlString:URLString completed:completed];
    }];
}

/**
 * 浅层网络请求封装-JSON 数据上传
 * 目的：网络请求可以集中处理，也可以解耦
 * 每个网络请求都附带一个模型文件承载服务器返回的数据
 * @author Sam
 */
+(void)seg_requestJSONWithMethod:(SEGHTTPSessionManagerRequestMethod)method URLString:(NSString*)URLString parameters:(id)parameters completed:(SEGReponseBlock)completed{
    
    URLString = [self seg_setRequestChangeUrl:URLString];
    [self seg_setRequestHeaderFieldWithUrlString:URLString];
    [self seg_setTimeoutIntervalWithUrlString:URLString];
    
    [[SEGHTTPManager sharedNetworkManager] requestJSONWithMethod:method URLString:URLString parameters:parameters finished:^(id result, NSError *error) {
        [self seg_responseLogicControlWithData:result error:error urlString:URLString completed:completed];
    }];
}

/* ---------------拆包之前的网络请求-------------*/
+(void)seg_requestWithMethod:(SEGHTTPSessionManagerRequestMethod)method URLString:(NSString*)URLString parameters:(id)parameters finished:(SEGNetworkReponse)finished{
    [self seg_requestWithMethod:method URLString:URLString parameters:parameters completed:^(BOOL isSuccessed, id result, NSString *codeType, NSError *error) {
        finished(isSuccessed,result,codeType,error.localizedDescription);
        return;
    }];
}
+(void)seg_requestJSONWithMethod:(SEGHTTPSessionManagerRequestMethod)method URLString:(NSString*)URLString parameters:(id)parameters finished:(SEGNetworkReponse)finished{
    [self seg_requestJSONWithMethod:method URLString:URLString parameters:parameters completed:^(BOOL isSuccessed, id result, NSString *codeType, NSError *error) {
        finished(isSuccessed,result,codeType,error.localizedDescription);
        return;
    }];
}

/**
 * 招商局请求 到家汇
 * @author Sam
 */
+ (void)seg_requestMerchantWithMethod:(SEGHTTPSessionManagerRequestMethod)method
                            URLString:(NSString*)URLString
                           parameters:(id)parameters
                            dataClass:(Class)className
                             finished:(SEGNetworkReponse)finished{
    
    URLString = [self seg_setRequestChangeUrl:URLString];
    [self seg_setRequestHeaderFieldWithUrlString:URLString];
    [self seg_setTimeoutIntervalWithUrlString:URLString];
    
    [[SEGHTTPManager sharedNetworkManager] requestWithMethod:method URLString:URLString parameters:parameters finished:^(id result, NSError *error) {
        [self seg_responseMerchantLogicControlWithData:result error:error urlString:URLString dataClass:className finished:finished];
    }];
}
/**
 * 网络请求回调的集中处理-招商
 * @author Sam
 */
+(void)seg_responseMerchantLogicControlWithData:(id)result error:(NSError*)error urlString:(NSString*)urlString dataClass:(Class)className finished:(SEGNetworkReponse)finished{
    
    if (result == nil || error != NULL) {
        finished(NO, result, @"", @"网络不太好，请稍后再试。"); //数据返回异常
        return;
    }
    if (![result isKindOfClass:[NSDictionary class]]) {
        finished(NO, result, @"-1", @"网络不太好，请稍后继续"); //数据返回异常
        return;
    }
    
    NSDictionary *resultDict = result;
    // 1、表示成功 ,Data显示结果集返回Json格式数据,如没结果集返回则返回ErrMsg提示语。非1、表示失败,ErrMsg显示错误提示信息,Data返回null ，-5：为token失效
    NSString *errCode = [SEGHTTPBusinessManager ValueToString:resultDict[@"ErrCode"]];
    NSString *errMsg = [SEGHTTPBusinessManager ValueToString:resultDict[@"ErrMsg"]];
    
    if ([errCode isEqualToString:@"-4"]) {//-4：为token失效 跳转到主界面
        //[[NSNotificationCenter defaultCenter] postNotificationName:SEGPopToRootViewControllerNotification object:errMsg];
        finished(NO, nil, errCode, errMsg);
        return;
    }
    
    if (![errCode isEqualToString:@"1"]) {
        finished(NO, nil, errCode, errMsg);
        return;
    }
    
    if (!resultDict[@"Data"]) {
        finished(NO, result, errCode, errMsg);
        return;
    }
    
    if (!className) {
        finished(YES, resultDict[@"Data"], errCode, errMsg);
        return;
    }
    
    if (![resultDict[@"Data"] isKindOfClass:className]) {
        finished(NO, result, errCode, errMsg);
        return;
    }
    
    finished(YES, resultDict[@"Data"], errCode, errMsg);
    return;
}

/**
 * 任意对象类数据类型转成NSString
 * @author Sam
 * @param objStr 任意类型的数据
 */
+ (NSString*)ValueToString:(id)objStr
{
    if ([objStr isEqual:nil]) {
        return [NSString string];
    }
    
    if ([objStr isEqual:[NSNull null]]) {
        return [NSString string];
    }
    
    if ([objStr isKindOfClass:[NSString class]]) {
        return objStr;
    }
    
    if ([objStr isKindOfClass:[NSNumber class]]) {
        return [NSString stringWithFormat:@"%@", objStr];
    }
    
    return [NSString string];
}


/**
 * 改变请求地址域名
 * @author Sam
 */
+(NSString*)seg_setRequestChangeUrl:(NSString*)urlString{
    // Platform从Common中抽出
    return urlString;
}

/**
 * 动态设置请求头
 * @author Sam
 */
+ (void)seg_setRequestHeaderFieldWithUrlString:(NSString *)urlString {
    //NSMutableDictionary *httpHeaderDic = [NSMutableDictionary dictionary];
    //    [httpHeaderDic setObject:kAppPlatformCode forKey:@"platform"];
    //    [httpHeaderDic setObject:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] forKey:@"version"];
    //    [httpHeaderDic setObject:[SEGUtils segUUIDString] forKey:@"deviceId"];
    //    [httpHeaderDic setObject:[self seg_sysCode:urlString] forKey:@"SYSCODE"];
    //    [httpHeaderDic setObject:[SEGUtils segDeviceHardWareName] forKey:@"phoneModel"];//手机机型
    //    [httpHeaderDic setObject:[SEGUtils segDeviceSystemVersion] forKey:@"systemVersionCode"];//系统
    //    [httpHeaderDic setObject:kSource forKey:@"sou1rce"];//系统
    //    NSString *communityId = [[NSUserDefaults standardUserDefaults]objectForKey:@"SEGUserDefaultsJobCommunity"];
    //    [httpHeaderDic setObject:ValueToString(communityId) forKey:@"communityId"]; //有存在逻辑控制
    //    [httpHeaderDic setObject:[SEGHTTPBusinessServerUrlList segAPiCode] forKey:@"versionCode"]; //接口版本号
    //    if (httpHeaderDic.allKeys.count <= 0) return;
    //[SEGHTTPManager sharedNetworkManager].headerFields = httpHeaderDic;
    
    NSDictionary *data = [[NSUserDefaults standardUserDefaults]objectForKey:@"NSUserDefaultRequestHeaderDictionary"];
    NSMutableDictionary *tmp = [NSMutableDictionary dictionaryWithDictionary:data];
    [tmp setValue: [self seg_sysCode:urlString] forKey:@"SYSCODE"];
    
    // 手动管理cookie
    NSString *cookieStr = [SEGHTTPManager seg_getCookiesDictionaryWithURL:[NSURL URLWithString:urlString]];
    if ([cookieStr isKindOfClass:[NSString class]]) {
        [tmp setValue:cookieStr forKey:@"Cookie"];
    }
    
    [SEGHTTPManager sharedNetworkManager].headerFields = [tmp copy];
}

/**
 * 动态设置网络请求的超长时间
 * @author Sam
 */
+(void)seg_setTimeoutIntervalWithUrlString:(NSString*)urlString{
    NSTimeInterval timeoutInterval = 10.0;
    if ([urlString rangeOfString:@"/cms-api/isShowAdvert"].location != NSNotFound) {
        [SEGHTTPManager sharedNetworkManager].timeoutInterval = 2.0;
    }else{
        [SEGHTTPManager sharedNetworkManager].timeoutInterval = timeoutInterval;
    }
}

/**
 * 网络请求回调的集中处理
 * @author Sam
 */
+(void)seg_responseLogicControlWithData:(id)result error:(NSError*)error urlString:(NSString*)urlString completed:(SEGReponseBlock)completed{
    if (result == nil || error != NULL) {
        //v5.2.0修改: 当服务器数据无返回或响应有误的时候，返回网络请求状态（网络门禁业务需要用到）
        completed(NO, nil, @"-1", [NSError errorWithDomain:NSCocoaErrorDomain code:error.code userInfo:@{NSLocalizedDescriptionKey:@"网络不太好，请稍后再试。"}]); //数据返回异常
        return;
    }
    
    if (![result isKindOfClass:[NSDictionary class]]) {
        completed(NO, result, @"-1", [NSError errorWithDomain:NSCocoaErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey:@"后台返回数据结构不规范！"}]);
        return;
    }
    
    NSString *code = [[result allKeys]containsObject:@"code"] ? [result valueForKey:@"code"] : @"-1";
    if (![code isKindOfClass:[NSString class]]) {
        code = [NSString stringWithFormat:@"%@", code];
    }
    
    NSString *message = [[result allKeys]containsObject:@"message"] ? [result valueForKey:@"message"] : @"";
    
    if ([code isEqualToString:@"0000001"] ||[code isEqualToString:@"0000002"]) {//没有登录
        [[SEGHTTPManager sharedNetworkManager]removeCookies];//登录前清除cookies
        completed(NO, result, code, [NSError errorWithDomain:NSCocoaErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey:message}]);
        [[SEGUhomeMediator sharedInstance]seg_pushToLoginViewController:@{@"message":@"您的账号未登录，请重新登录"}];
        [[SEGHTTPManager sharedNetworkManager] segCancelAllRequest];
        return;
    }
    
    if ([code isEqualToString:@"-1"]) {
        completed(NO, result, code, [NSError errorWithDomain:NSCocoaErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey:message}]);
        return;
    }
    
    // 只有code是0的时候 才是success
    if ([code isEqualToString:@"0"]) {
        completed(YES, result, code, [NSError errorWithDomain:NSCocoaErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey:message}]);
    } else {
        //v5.2.0修改: 当服务器数据无返回或响应有误的时候，返回网络请求状态（网络门禁业务需要用到）
        completed(NO, result, code, [NSError errorWithDomain:NSCocoaErrorDomain code:error.code userInfo:@{NSLocalizedDescriptionKey:message}]);
    }
}

/**
 * SYSCODE 请求头
 * @author Sam
 * @param url 请求地址
 * @return 请求头编码
 */
+ (NSString*)seg_sysCode:(NSString*)url{
    
    NSString* sysCode = @"";
    
    if ([url rangeOfString:kUhomecp_sso].location != NSNotFound) {
        sysCode = @"10";
    }
    else if ([url rangeOfString:kUhomecp_app].location != NSNotFound) {
        sysCode = @"20";
    }
    else if ([url rangeOfString:kCMS_api].location != NSNotFound) {
        sysCode = @"30";
    }
    else if ([url rangeOfString:kUser_service].location != NSNotFound) {
        sysCode = @"40";
    }
    else if ([url rangeOfString:kUhomecp_admin].location != NSNotFound) {
        sysCode = @"50";
    }
    else if ([url rangeOfString:kEcommerce].location != NSNotFound) {
        sysCode = @"60";
    }
    return sysCode;
}
@end
